package com.seafood.controller;

import com.seafood.common.Result;
import com.seafood.dto.SendSmsRequestDTO;
import com.seafood.dto.SmsVerificationCodeDTO;
import com.seafood.dto.VerifySmsCodeRequestDTO;
import com.seafood.service.SmsVerificationCodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 短信验证码控制器
 */
@RestController
@RequestMapping("/api/sms")
@RequiredArgsConstructor
public class SmsVerificationCodeController {
    
    private final SmsVerificationCodeService smsVerificationCodeService;
    
    // 发送短信验证码
    @PostMapping("/send")
    public ResponseEntity<Result<SmsVerificationCodeDTO>> sendVerificationCode(
            @Valid @RequestBody SendSmsRequestDTO requestDTO,
            HttpServletRequest request) {
        
        String ipAddress = getClientIpAddress(request);
        String userAgent = request.getHeader("User-Agent");
        
        SmsVerificationCodeDTO result = smsVerificationCodeService.sendVerificationCode(requestDTO, ipAddress, userAgent);
        return ResponseEntity.ok(Result.success("验证码发送成功", result));
    }
    
    // 验证短信验证码
    @PostMapping("/verify")
    public ResponseEntity<Result<Boolean>> verifyCode(
            @Valid @RequestBody VerifySmsCodeRequestDTO requestDTO,
            HttpServletRequest request) {
        
        String ipAddress = getClientIpAddress(request);
        boolean isValid = smsVerificationCodeService.verifyCode(requestDTO, ipAddress);
        
        if (isValid) {
            return ResponseEntity.ok(Result.success("验证码验证成功", true));
        } else {
            return ResponseEntity.ok(Result.error("验证码无效或已过期"));
        }
    }
    
    // 验证并使用验证码
    @PostMapping("/verify-and-use")
    public ResponseEntity<Result<Boolean>> verifyAndUseCode(
            @Valid @RequestBody VerifySmsCodeRequestDTO requestDTO,
            HttpServletRequest request) {
        
        String ipAddress = getClientIpAddress(request);
        boolean isValid = smsVerificationCodeService.verifyAndUseCode(requestDTO, ipAddress);
        
        if (isValid) {
            return ResponseEntity.ok(Result.success("验证码验证成功", true));
        } else {
            return ResponseEntity.ok(Result.error("验证码无效或已过期"));
        }
    }
    
    // 重新发送验证码
    @PostMapping("/resend")
    public ResponseEntity<Result<SmsVerificationCodeDTO>> resendVerificationCode(
            @RequestParam String phone,
            @RequestParam String codeType,
            HttpServletRequest request) {
        
        String ipAddress = getClientIpAddress(request);
        String userAgent = request.getHeader("User-Agent");
        
        SmsVerificationCodeDTO result = smsVerificationCodeService.resendVerificationCode(phone, codeType, ipAddress, userAgent);
        return ResponseEntity.ok(Result.success("验证码重新发送成功", result));
    }
    
    // 获取最新验证码信息（不包含具体验证码）
    @GetMapping("/latest")
    public ResponseEntity<Result<SmsVerificationCodeDTO>> getLatestCode(
            @RequestParam String phone,
            @RequestParam String codeType) {
        
        SmsVerificationCodeDTO result = smsVerificationCodeService.getLatestCodeByPhoneAndType(phone, codeType);
        if (result != null) {
            return ResponseEntity.ok(Result.success(result));
        } else {
            return ResponseEntity.ok(Result.error("未找到有效的验证码"));
        }
    }
    
    // 获取发送历史
    @GetMapping("/history")
    public ResponseEntity<Result<List<SmsVerificationCodeDTO>>> getSendHistory(
            @RequestParam String phone,
            @RequestParam(defaultValue = "10") int limit) {
        
        List<SmsVerificationCodeDTO> history = smsVerificationCodeService.getSendHistory(phone, limit);
        return ResponseEntity.ok(Result.success(history));
    }
    
    // 检查发送频率限制
    @GetMapping("/check-frequency")
    public ResponseEntity<Result<Boolean>> checkSendFrequency(
            @RequestParam String phone,
            @RequestParam String codeType,
            HttpServletRequest request) {
        
        String ipAddress = getClientIpAddress(request);
        boolean canSend = smsVerificationCodeService.checkSendFrequency(phone, codeType, ipAddress);
        
        if (canSend) {
            return ResponseEntity.ok(Result.success("可以发送验证码", true));
        } else {
            return ResponseEntity.ok(Result.success("发送过于频繁，请稍后再试", false));
        }
    }
    
    // 获取发送统计信息（管理员功能）
    @GetMapping("/statistics")
    public ResponseEntity<Result<Map<String, Object>>> getSendStatistics(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        
        Map<String, Object> statistics = smsVerificationCodeService.getSendStatistics(startDate, endDate);
        return ResponseEntity.ok(Result.success(statistics));
    }
    
    // 获取频繁发送用户列表（管理员功能）
    @GetMapping("/frequent-senders")
    public ResponseEntity<Result<List<Map<String, Object>>>> getFrequentSenders(
            @RequestParam(defaultValue = "7") int days,
            @RequestParam(defaultValue = "50") int threshold) {
        
        List<Map<String, Object>> senders = smsVerificationCodeService.getFrequentSenders(days, threshold);
        return ResponseEntity.ok(Result.success(senders));
    }
    
    // 清理过期验证码（管理员功能）
    @PostMapping("/cleanup")
    public ResponseEntity<Result<String>> cleanupExpiredCodes() {
        smsVerificationCodeService.cleanupExpiredCodes();
        return ResponseEntity.ok(Result.success("过期验证码清理完成"));
    }
    
    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}